package com.xing.service.impl;

import com.xing.dao.UserDao;
import com.xing.dao.impl.UserDaoImpl;
import com.xing.domain.User;
import com.xing.service.UserService;
import com.xing.utils.DataSourceUtils;

import java.sql.SQLException;

/*
 * 静，谦虚谨慎，心胸宽广容纳所有好的坏的、先苦后甜
 * day38web2
 * 2021/4/28 15:39
 */
public class UserServiceImpl implements UserService {
    private UserDao userDao=new UserDaoImpl();
    @Override
    public void regist(User user) {
        try {
            DataSourceUtils.begin();
            //验证用户是否存在
            boolean b = userDao.selectByUserName(user.getUsername());
            if(b){
                throw new RuntimeException("用户名已存在");
            }
            userDao.insert(user);
            DataSourceUtils.commit();
        } catch (Exception e) {
            try {
                DataSourceUtils.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            throw new RuntimeException(e);
        } finally {
            try {
                DataSourceUtils.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    @Override
    public User login(String username, String password) {
        User user = userDao.selectByUserAndPassword(username, password);
        if(user==null){
            throw new RuntimeException("用户名或者密码错误");
        }
        if(user.getFlag()!=1){
            throw new RuntimeException("账户未激活或已失效");
        }
        return user;
    }
}
